package com.tianhui.consignortwofei.mvp.model.enty.ocrResult.businessLicense;

import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.Word;
import com.baidu.ocr.sdk.utils.Parser;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author fgs
 * @date 2021/6/25
 * @description
 **/
public class BusinessLicenseResultParser implements Parser<BusinessLicenseResult> {
    public BusinessLicenseResultParser() {
    }

    public BusinessLicenseResult parse(String json) throws OCRError {
        OCRError error;
        try {
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.has("error_code")) {
                error = new OCRError(jsonObject.optInt("error_code"), jsonObject.optString("error_msg"));
                error.setLogId(jsonObject.optLong("log_id"));
                throw error;
            } else {
                BusinessLicenseResult result = new BusinessLicenseResult();
                JSONObject wordResult = jsonObject.optJSONObject("words_result");
                if (wordResult != null) {
                    result.setSocialCreditCode(this.map(wordResult.optJSONObject("社会信用代码")));
                    result.setUnitName(this.map(wordResult.optJSONObject("单位名称")));
                    result.setAddress(this.map(wordResult.optJSONObject("地址")));
                    result.setLegalPerson(this.map(wordResult.optJSONObject("法人")));
                    result.setStartDate(this.map(wordResult.optJSONObject("成立日期")));
                    result.setEndDate(this.map(wordResult.optJSONObject("有效期")));
                    result.setType(this.map(wordResult.optJSONObject("类型")));
                    result.setBusinessNature(this.map(wordResult.optJSONObject("经营范围")));
                    result.setRegisteredCapital(this.map(wordResult.optJSONObject("注册资本")));
                }
                return result;
            }

        } catch (JSONException var5) {
            error = new OCRError(283505, "Server illegal response " + json, var5);
            throw error;
        }
    }

    private Word map(JSONObject jsonObject) {
        Word word = null;
        if (jsonObject != null) {
            word = new Word();
            word.setWords(jsonObject.optString("words"));
        }

        return word;
    }
}
